<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene"></Category>
  </div>

  <el-card style="margin: 10px 0;">
    <div v-show="scene == 0">
      <el-button @click="addAttr" type="primary" size="default" icon="Plus"
        :disabled="categoryStore.c3Id ? false : true">添加属性</el-button>
      <el-table border style="margin: 10px 0px;" :data="attrArr">
        <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
        <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-tag style="margin: 5px;" type="default" v-for="(item, index) in row.attrValueList" :key="item.id">
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ row, $index }">
            <!-- 修改已有属性值按钮 -->
            <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
            
            <el-popconfirm :title="`你确定要删除吗${row.attrName}`" @confirm="deleteAttr(row.id)">
              <template #reference>
                <el-button type="primary" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="scene == 1">
      <!-- 添加与修改属性 -->
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="addAttrValue" type="primary" icon="Plus" :disabled="!attrParams.attrName">添加属性值</el-button>
      <el-button @click="cancel">取消</el-button>
      <el-table border style="margin: 10px 0;" :data="attrParams.attrValueList">
        <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
        <el-table-column label="属性值名称">
          <!-- row为当前属性值对象 -->
          <template #="{ row, $index }">
            <el-input :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row, $index)" size="small"
              v-model="row.valueName" placeholder="请你输入属性值名称"></el-input>
            <div v-else @click="toEdit(row, $index)">
              {{ row.valueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作">
          <template #="{row,$index}">
            <el-button type="danger" size="small" icon="Delete" @click="attrParams.attrValueList.splice($index,1)"></el-button>
          </template>        
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="save"
        :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
      <el-button @click="cancel" >取消</el-button>
    </div>
  </el-card>
</template>
<script setup lang='ts' name='attr'>
import useCategoryStore from '@/store/modules/category';
import type { AttrResponseData, Attr, AttrList, AttrValue } from '@/api/product/attr/type';
import { reqAddorUpdateAttr, reqAttr,reqRemoveAttr } from '@/api/product/attr';
import { nextTick, onBeforeUnmount, reactive, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
//获取分类的仓库   查看是否有c3分类Id来获取请求
let categoryStore = useCategoryStore()
//存储已有的属性与属性值
let attrArr = ref<Attr[]>([])
//定义card组件内容切换变量  scene==0 显示table  ==1显示添加属性场景
let scene = ref<number>(0)
//收集新增或更新属性的数据
let attrParams = reactive<Attr>({
  attrName: '',      //新增属性名
  attrValueList: [], //新增属性值
  categoryId: '',   //新增属性所属三级分类id
  categoryLevel: 3, //代表的是三级分类
})
//准备一共数组存放input组件来聚焦
let inputArr = ref<any>([])

//监听仓库三级分类Id变化
watch(() => categoryStore.c3Id, () => {
  //清空上一次查询的属性与属性值
  attrArr.value = []
  //保证三级分类有才发请求
  if (!categoryStore.c3Id) return
  //获取分类ID
  getAttr()

})
//获取已有的属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code == 200) {
    attrArr.value = result.data
  }
}
//添加按钮回调
const addAttr = () => {
  //每一次点击时清空数据
  Object.assign(attrParams, {
    attrName: '',      //新增属性名
    attrValueList: [], //新增属性值
    categoryId: categoryStore.c3Id,   //新增属性所属三级分类id 清空时顺便收集
    categoryLevel: 3, //代表的是三级分类
  })
  //场景切换
  scene.value = 1
}

//table表格修改按钮回调
const updateAttr = (row:Attr) => {
  //场景切换
  scene.value = 1
  //!!!!!!!!Object.assign是浅拷贝 两者指向同一个地方 只要更改attrParams，就算点取消按钮，也会影响原来的属性中的值
  // Object.assign(attrParams,row)
  //此为深拷贝 
  // JSON.stringify(row): 将row对象=>json对象    
  // JSON.parse(...) :将字符串转为json对象
  Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
}
//取消属性添加按钮回调
const cancel = () => {
  scene.value = 0
}
//添加属性值回调
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, //控制每一个属性值编辑与查看模式的切换
  })
  //获取最后input聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length-1].focus()
  })
}
//保存属性值数据
const save = async () => {
  //发请求
  let result: any = await reqAddorUpdateAttr(attrParams)
  if (result.code == 200) {
    //切换场景
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}
//属性值失去焦点回调
const toLook = (row: AttrValue, $index: number) => {
  //非法1 空判断
  if (row.valueName.trim() == '') {
    //删除为空的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: "属性值不能为空",
    })
    return
  }
  //非法2 输入相同属性值
  let repeat = attrParams.attrValueList.find((item) => {
    /* 
    find() 是 JavaScript 数组的方法，用于查找数组中 第一个满足条件 的元素。
    return item.valueName === row.valueName
    如果 item 的 valueName 和 row 的 valueName 相同
    ，则返回 true，此时 find() 会停止遍历并返回这个 item。 */
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    //删除重复的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: "属性值不能重复",
    })
    return
  }


  row.flag = false
}
//点击属性值变为编辑模式
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
//删除某一个已有属性按钮回调
const deleteAttr = async(attrId:number) => {
  let result = await reqRemoveAttr(attrId)
  if(result.code == 200){
    //删除成功
    ElMessage({
      type: 'success',
      message: "删除成功",
    })
    //获取一次已有的属性与属性值
    getAttr()
  }else{
    //删除成功
    ElMessage({
      type: 'error',
      message: "删除失败",
    })
  }
}

//路由组件切换销毁时，清空仓库东西
onBeforeUnmount(() => {
  categoryStore.$reset()
})

</script>


<style scoped></style>